package cn.edu.neu.controller.manage;

import cn.edu.neu.model.Category;
import cn.edu.neu.model.Goods;
import cn.edu.neu.model.User;
import cn.edu.neu.service.CategoryService;
import cn.edu.neu.service.GoodsService;
import cn.edu.neu.utils.FileUploadUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@Controller
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/manage/goods")
    public String getGoodsList(@RequestParam(value = "page", defaultValue = "1") int page,
                               @RequestParam(value = "count", defaultValue = "6") int count,
                               HttpServletRequest request){
        PageInfo<Goods> goods = goodsService.getGoodsList(page,count);
        request.setAttribute("goods",goods);
        return "manage/goods/goods_list";
    }




    @GetMapping("/manage/find_goods")//,@PathVariable String find_goods
    public String find_goods_byName(@RequestParam(value = "page", defaultValue = "1") int page,
                               @RequestParam(value = "count", defaultValue = "6") int count,
                               HttpServletRequest request,@RequestParam(value = "find_goods") String find_goods){
        System.out.println("find_goods是："+find_goods);
        PageInfo<Goods> goods = goodsService.FindGoodsByName(page,count,find_goods);
        request.setAttribute("goods",goods);
        return "manage/goods/goods_list";
    }

    //manage/goods/addGoods

    @GetMapping("/manage/goods/addGoods")//
    public String addGoods(Model model,Goods goods){
        List<Category> categories =  categoryService.findAllCategory();
        model.addAttribute("cates",categories);
        model.addAttribute("goods",goods);
        return "manage/goods/goods_add";
    }


    ///manage/goods/doHandleGoods
    @PostMapping("/manage/goods/doHandleGoods")//
    public String doHandleGoods(MultipartFile goodsPicFile,Goods goods){
        //保持图片
        if (!goodsPicFile.isEmpty()) {
            System.out.println("=========dirPath=1111");
            String path = "/static/images/cate/";
            Map upload = FileUploadUtil.uploadFile(goodsPicFile, path);
            goods.setGoods_pic(upload.get("cate_pic").toString());
        }
        goodsService.addGoods(goods);

        return "redirect:/manage/goods";
    }
}
